import React from "react";
import "./index.less";
import MDEditor from "@uiw/react-md-editor";
import { Form, Input, Button, Switch, Divider, message, Upload } from "antd";
import { UploadOutlined } from "@ant-design/icons";
const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
};
const tailLayout = {
  wrapperCol: { offset: 2, span: 22 },
};
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default class Add extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "**Hello world!!!**",
      title: "",
      type: 0,
      id: "",
      fileList: ''
    };
  }
  componentDidMount() {
    if (this.props.history.location.state) {
      // 编辑
      this.setState({ type: 1, id: this.props.history.location.state.id });
      this.getData(this.props.history.location.state.id);
    }
  }
  componentWillUnmount() {
    this.setState = () => false;
  }
  getData = (id) => {
    this.get("/admin/blog/info/" + id, "")
      .then((res) => {
        if (res.code === 200) {
          this.formRef.current.setFieldsValue({
            title: res.data.title,
            is_enable:
              res.data.is_enable &&
              res.data.is_enable.data.length &&
              res.data.is_enable.data[0] === 1,
          });
          this.setState({ img: res.data.img })
          this.setValue(res.data.detail);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
  formRef = React.createRef();
  setValue = (value) => {
    this.setState({
      value: value,
    });
  };
  onFinish = async (values) => {
    let data = {
      detail: this.state.value,
      ...values,
    };
    if (data.upload && data.upload.length) {
      let img = await this.getBase64(data.upload[0].originFileObj)
      data.img = img;
      delete data.upload;
    } else {
      data.img = '';
      delete data.upload;
    }
    if (!this.state.type) {
      this.post("/admin/blog/add", data).then((res) => {
        if (res.code === 200) {
          message.success("操作成功");
          this.goBack();
        }
      });
    } else {
      data.id = this.state.id;
      this.post("/admin/blog/update", data).then((res) => {
        if (res.code === 200) {
          message.success("操作成功");
          this.goBack();
        }
      });
    }
  };

  onFinishFailed(errorInfo) {
    console.log("Failed:", errorInfo);
  }

  goBack = () => {
    this.props.history.push({
      pathname: "list",
    });
  }

  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }
  handleChange = async info => {
    getBase64(info.file, img =>
      this.setState({
        img,
      }),
    );
  }

  getBase64 = (file) => {
    return new Promise(function (resolve, reject) {
      let reader = new FileReader();
      let imgResult = "";
      reader.readAsDataURL(file);
      reader.onload = function () {
        imgResult = reader.result;
      };
      reader.onerror = function (error) {
        reject(error);
      };
      reader.onloadend = function () {
        resolve(imgResult);
      };
    });
  }

  render() {
    const fileList = this.state.fileList;
    const props = {
      onChange: this.handleChange,
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
    };
    return (
      <div className="add-container">
        <div className="add-container-header">
          <span>{this.state.type ? "编辑" : "新增"}</span>
          <Divider type="vertical" />
          <Button type="link" onClick={this.goBack}>
            {this.state.type ? "返回列表" : "查看列表"}
          </Button>
        </div>

        <MDEditor
          height={400}
          value={this.state.value}
          onChange={this.setValue}
        />
        <div className="main">
          <Form
            {...layout}
            ref={this.formRef}
            name="basic"
            onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}
          >
            <Form.Item
              label="标题"
              name="title"
              initialValue={this.state.title}
              rules={[{ required: true, message: "请输入标题" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="upload"
              label="封面图"
              valuePropName="fileList"
              getValueFromEvent={this.normFile}
            >
              <Upload maxCount={1} {...props} listType="picture" showUploadList={false}>
                {this.state.img ? <img className="preImg" src={this.state.img} alt="avatar" /> : <Button icon={<UploadOutlined />}>选择图片</Button>}
              </Upload>
            </Form.Item>

            <Form.Item
              name="is_enable"
              label="是否启用"
              valuePropName="checked"
              initialValue={true}
            >
              <Switch />
            </Form.Item>

            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
            </Form.Item>
          </Form>
        </div>
        {/* <MDEditor.Markdown source={value} /> */}
      </div>
    );
  }
}
